<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>canvas</title>
</head>
<body>
<canvas width="1000" height="700" id="pad" style="border: 1px solid black;background: black"></canvas>

</body>
<script>
    //需求：1.鼠标移入画布时自动画小球
    //      2.所画的小球随机填充颜色
    //      3.小球做自由落体运动
    //      4.运动到底部有回落（模拟一个球落地的状态）
    //步骤：1创建画布并确定画布的环境时2d的
    var pad = document.getElementById('pad');
    var ctx = pad.getContext('2d');

    //2.用面向对象的方法来绘制小球
    var ballList = [];//用来放画好的小球
    function Ball(x,y,r,vx,vy,col) {
        //x、y小球圆心位置
        this.x = x;
        this.y = y;
        this.r = r;//半径
        this.vx = vx;
        this.vy = vy;
        this.gravity = 0.5;//重力加速度
        this.col = col;
        this.drawBall = function () {
            ctx.beginPath();
            ctx.fillStyle = col;
            ctx.arc(this.x, this.y, this.r, 0, 2 * Math.PI, true);
            ctx.fill()
        };
        this.move = function () {
            ctx.fill();
            this.x = this.x + this.vx;
            this.y = this.y + this.vy;
            this.vy = this.vy + this.gravity;
            if(this.y > pad.height - this.r){//到边界时改变运动方向
                this.vy = this.vy*-0.9;
                this.vx = this.vx*0.9
            }
            if(Math.abs(this.vy) < 0.2 && this.y>pad.height-this.r){//y方向的运动范围控制
                this.gravity = 0;
                this.vy = 0;
            }
            if(this.x>pad.width-this.r || this.x < this.r){//x方向的边界处理（相当于碰撞检测）
                this.vx =this.vx*-1
            }
            if(this.vy==0){
                this.vx = this.vx*0.98;
            }
        }
    }
    var newBall;

    pad.timer = null;
    pad.onmousedown = function (ev) {
        clearInterval(this.timer);
        this.timer = setInterval(function () {
            var num = Math.floor(Math.random()*225),
                    num1 = Math.floor(Math.random()*225),
                    num2 = Math.floor(Math.random()*225);//随机生成0-225的数
            var str = 'rgba('+ num +','+ num1+','+ num2 +',0.8)';//颜色随机(此处的三个数是三个不同的变量)
            var r = Math.random()*50+1;//半价随机
            var vx = Math.random()*10-5;//
            newBall = new Ball(ev.clientX,ev.clientY,r,vx,0,str);
            newBall.drawBall();
            ballList.push(newBall);
        },20);
        document.onmouseup = function () {
            clearInterval(pad.timer);
        }
    };
    setInterval(function () {
        ctx.clearRect(0,0,pad.width,pad.height);//清空当前的画布
        for (var i = 0; i < ballList.length; i++) {
            var obj = ballList[i];
            obj.drawBall();
            obj.move()
        }
    },10)



</script>
</html>